<?php

namespace app\api\controller;

use app\admin\model\District;
use app\admin\model\money\Change;
use app\admin\model\product\Listo;
use app\admin\model\product\Order;
use app\admin\model\total\Bill;
use app\admin\model\user\Finance;
use app\admin\model\user\Sign;
use app\admin\model\user\Statics;
use app\common\controller\Api;
use app\common\controller\Bonus;
use app\common\model\Area;
use app\common\model\Config;
use think\Request;
use think\Db;

/**
 * 地址接口
 */
class Task extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $model = null;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

    }

    /**
     * 储存钱包每日利息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function dayEarning()
    {
        $profile_time = config('site.profile_time');
        $today = strtotime('today');
        if ($profile_time >= $today) {
            $this->error('今日已结算收益！');
        }

        $staticRate = config('site.static_rate');
        if ($staticRate <= 0) {
            echo '今日无收益';
            die;
        }

        $finances = Finance::field('id,user_id,profile,hasmoney,allmoney')->where('hasmoney', '>', 0)->order('id asc')->select();
        if (!$finances) {
            echo '今日无储存币';
            die;
        }
        foreach ($finances as $val) {
            $userId = $val['user_id'];
            $user = \app\admin\model\User::find($userId);

            if ($user->status != 'normal') {
                continue;
            }
            $money = round(($val['hasmoney'] - $val['profile']) * $staticRate * 0.01, 2);
            $val->profile += $money;
            $val->hasmoney += $money;
            $val->allmoney += $money;

            Db::startTrans();
            try {

                $val->save();

                $orderNum = create_order($userId);
                $mdata = [
                    'order_num' => $orderNum,
                    'record_type' => 1,
                    'change_type' => 10,
                    'moneytype' => 6,
                    'money' => $money,
                    'hasmoney' => $val->hasmoney,
//                'remark' => $tag,
                    'user_id' => $val['user_id'],
                    'targetuserid' => $val['user_id']
                ];
                Change::create($mdata);

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $now = time();
        Config::where('name', 'profile_time')->setField('value', $now);
        config('site.profile_time', $now);

        echo 'success';
        die;
    }

    /**
     * 合伙人收益（日结周发）
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusDivid()
    {
        $achievement = Config::where('name', 'achievement')->value('value');

        if ($achievement > 0) {
            $users = \app\admin\model\User::where('status', 'normal')->where('is_partner', 1)->select();
            $number = count($users);
            if ($number > 0) {
                $total = $achievement * config('site.partner_rate') * 0.01;
                $dividMoney = round($total / $number, 2);
                if ($dividMoney > 0) {
                    foreach ($users as $val) {
                        \app\admin\model\User::where('id', $val->id)->setInc('bonus5', $dividMoney);
                    }

                    Config::where('name', 'achievement')->setField('value', 0);
                }
            }
        }

        $date = date('w', time());
        if ($date == 1) {
            $nusers = \app\admin\model\User::where('status', 'normal')->where('is_partner', 1)->where('bonus5', '>', 0)->select();
            $nnumber = count($nusers);
            if ($nnumber <= 0) {
                return;
            }

            foreach ($nusers as $val) {
                $ndividMoney = $val->bonus5;
                self::bonusShare($ndividMoney, 5, $val['id']);

                \app\admin\model\User::where('id', $val->id)->setField('bonus5', 0);
            }
        }

        echo 'success';
        die;
    }

    /**
     * 次日自动排队结算
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function queueBonus()
    {
        $bonus_time = config('site.bonus_time');
        $stoday = strtotime('today');
        if ($bonus_time >= $stoday) {
            $this->error('今日已结算收益！');
        }

        $today = date('Y-m-d', $stoday);
        $today_bill = Bill::where('time', $today)->value('total');
        if (!$today_bill) {
            $today_bill = config('site.total_bill');
        }

        $orders = Order::where('status', 5)->order('id asc')->select();
        if ($orders) {
            $total = 0;
            Db::startTrans();
            try {
                foreach ($orders as $val) {
                    $total += $val['total'];
                    if ($total > $today_bill) {
                        break;
                    }

                    $user_id = $val['user_id'];
                    $bonus = new Bonus($user_id, $val['total']);
                    $nums = Listo::where('order_id', $val['id'])->sum('num');
                    $bonus->giveMoney($nums);
                    $bonus->bonusRecom();
                    $bonus->bonusLevel();
                    $bonus->bonusHouse();
                    $bonus->bonusOperat();
                    \app\admin\model\User::where('id', $user_id)->setField('rank', 1);
                    $bonus->addAchievement();
                    $bonus->bonusUpdate();

                    $val->status = 6;
                    $val->save();
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $now = time();
        Config::where('name', 'bonus_time')->setField('value', $now);
        config('site.bonus_time', $now);

        echo 'success';
        die;
    }

    /**
     * 积分转化为收益
     * @throws \think\Exception
     */
    public function bonusStatic()
    {
        $tf_time = config('site.tf_time');
        $stoday = strtotime('today');
        if ($tf_time >= $stoday) {
            $this->error('今日已转化收益！');
        }

        $week = date('w', time());
//        $week = date('w', 1722096000);
        if ($week == 0) {
            echo '今日不转化';
            die;
        }

        $isTf = config('site.is_tf');
        if ($isTf !== "1") {
            echo '今日不转化';
            die;
        }

        $users = Finance::where('hasscore', '>', 0)->order('id asc')->select();
        $yesday = strtotime('today') - 24 * 60 * 60;
        foreach ($users as $val) {
            $userId = $val['user_id'];

            // 昨天未签到的不能转化
            $isSign = Sign::where('user_id', $userId)->where('createtime', '>=', $yesday)->find();
            if (!$isSign) {
                continue;
            }
            $statics = Statics::where('user_id', $userId)->find();
            if ($statics->totaled + $statics->money2 >= $val->hasscore) {
                $staticMoney = $val->hasscore;
            } elseif ($statics->total <= $statics->totaled) {
                $staticMoney = $statics->money2;
            } elseif ($statics->total <= ($statics->totaled + $statics->money1)) {
                $staticMoney = $statics->total - $statics->totaled;
            } else {
                $staticMoney = $statics->money1;
            }

            Db::startTrans();
            try {

                $val->hasscore -= $staticMoney;
                $val->save();

                $orderNum = create_order($userId);
                $mdata = [
                    'order_num' => $orderNum,
                    'record_type' => 0,
                    'change_type' => 9,
                    'moneytype' => 2,
                    'money' => $staticMoney,
                    'hasmoney' => $val->hasscore,
//                'remark' => $tag,
                    'user_id' => $val['user_id'],
                    'targetuserid' => $val['user_id']
                ];
                Change::create($mdata);

                $statics->totaled += $staticMoney;
                $statics->save();

                self::bonusShare($staticMoney, 9, $val['user_id']);

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $now = time();
        Config::where('name', 'tf_time')->setField('value', $now);
        config('site.tf_time', $now);

        echo 'success';
        die;
    }

    public function bonusShare($bonusmoney, $change_type, $userId)
    {
        $finance = Finance::where('user_id', $userId)->find();
        if ($change_type == 9) {
//            $tax_rate = config('site.tax_rate');
//            if ($tax_rate > 100 || $tax_rate <= 0) {
//                $tax = 0;
//            } else {
//                $tax = $tax_rate * 0.01;
//            }

            $static_to_moneys = config('site.static_to_moneys') * 0.01;
            $static_to_shop = config('site.static_to_shop') * 0.01;

//            $tax_money = round($bonusmoney * $tax, 2);
            $dMoney = round($bonusmoney * $static_to_moneys, 2);
            $sMoney = round($bonusmoney * $static_to_shop, 2);

            $finance->hasmoneys += $dMoney;
            $finance->allmoneys += $dMoney;
            $finance->hasshop += $sMoney;
            $finance->allshop += $sMoney;

            $moneytype = 3;
            $field = 'hasmoneys';

            $res = $finance->save();
        } else {
            $tax_rate = config('site.tax_rate');
            if ($tax_rate > 100 || $tax_rate <= 0) {
                $tax = 0;
            } else {
                $tax = $tax_rate * 0.01;
            }

            $tax_money = $bonusmoney * $tax;
            $actulMoney = $bonusmoney - $tax_money;
            $sMoney = 0;
            $dMoney = round($actulMoney, 2);

            $finance->hasmoneyd += $dMoney;
            $finance->allmoneyd += $dMoney;

            $moneytype = 4;
            $field = 'hasmoneyd';

            $finance->allbonus += $bonusmoney;
            $res = $finance->save();
        }

        if ($res) {

            if ($change_type == 5) {
                self::bonus('bonus_day', $change_type, $userId, $bonusmoney, $dMoney);
                self::bonus('bonus_total', $change_type, $userId, $bonusmoney, $dMoney);
            }

            $orderNum = create_order($userId);
            $mdata1 = [
                'order_num' => $orderNum,
                'record_type' => 1,
                'change_type' => $change_type,
                'moneytype' => $moneytype,
                'money' => $dMoney,
                'hasmoney' => $finance->$field,
//                'remark' => $tag,
                'user_id' => $userId,
                'targetuserid' => $userId
            ];

            Change::create($mdata1);

            if ($sMoney > 0) {
                $orderNum = create_order($userId);
                $mdata2 = [
                    'order_num' => $orderNum,
                    'record_type' => 1,
                    'change_type' => $change_type,
                    'moneytype' => 5,
                    'money' => $sMoney,
                    'hasmoney' => $finance->hasshop,
//                'remark' => $tag,
                    'user_id' => $userId,
                    'targetuserid' => $userId
                ];

                Change::create($mdata2);
            }
        }
    }

    private function bonus($table, $bonustype, $touid, $money, $hasmoney)
    {
        $touser = \app\admin\model\User::find($touid);
        if ($table == 'bonus_day') {
            $count_date = strtotime('today');
            $map['count_date'] = $count_date;
        } else {
            $count_date = time();
        }

        $BCount = Db($table);
        $map['user_id'] = $touid;
        $bonusData = $BCount->where($map)->find();
        $field = 'bonus' . $bonustype;
        if ($bonusData) {
            $data[$field] = $bonusData[$field] + $money;
            $data['total'] = $bonusData['total'] + $hasmoney;
            $data['tax_money'] = round($money - $hasmoney, 2);
            $BCount->where($map)->update($data);
        } else {
            $data = array(
                'user_id' => $touser['id'],
                'count_date' => $count_date
            );
            $data[$field] = $money;
            $data['total'] = $hasmoney;
            $data['tax_money'] = round($money - $hasmoney, 2);
            $BCount->insert($data);
        }
    }
}
